﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyTestProject.NUnity
{
    public class ReadWriteTxtHelper
    {
        /// <summary>
        /// 文件路径
        /// </summary>
        private  static string FilePath
        {
            get { return $"{AppDomain.CurrentDomain.BaseDirectory}Data//{ ConfigurationManager.AppSettings["ConfigPath"]}.txt"; }
        }

        /// <summary>
        /// 向txt文件中写入内容
        /// </summary>
        /// <param name="value">内容</param>
        /// <param name="isClearOldText">是否清除旧的文本</param>
        public static void WriteTxt(string value, bool isClearOldText = true)
        {
            if (isClearOldText)
            {
                using (FileStream stream = File.Open(FilePath, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    stream.SetLength(0);
                }
            }
            using (StreamWriter writer = new StreamWriter(FilePath, true))
            {
                writer.WriteLine(value);
            }
        }

        /// <summary>
        ///  向txt文件中追加内容
        /// </summary>
        /// <param name="value">内容</param>
        public static void WriteAppendTxt(string value)
        {
            StreamWriter sw = File.AppendText(FilePath);
            sw.WriteLine(value);
            sw.Flush();
            sw.Close();
            sw.Dispose();
        }

        /// <summary>
        /// 读取txt文件并返回文件中的内容
        /// </summary>
        /// <returns>txt文件内容</returns>
        public static string ReadTxt()
        {
            try
            {
                string result = string.Empty;
                using (StreamReader sr = new StreamReader(FilePath, Encoding.Default))
                {
                    string line;
                    while (!string.IsNullOrEmpty((line = sr.ReadLine())))
                    {
                        result += $"{line.Replace("\t\t","\t")}@";
                    }
                }
                return result.Substring(0, result.Length-1);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }
    }
}
